<script lang="ts" setup>
import type { LicenseInfo } from '@/types'
import type { FormInst } from 'nutui-uniapp'
import { useSteps } from '@/composables/useSteps'
import { useApplyStore } from '@/store'

interface Option {
  text: string
  value: string
  merType: string[]
}
const { licenseInfo, mer_type } = storeToRefs(useApplyStore())
const { next } = useSteps('cert')
const ruleForm = ref<FormInst | null>(null)
const licenseUploader = ref()
const form = ref<LicenseInfo>({
  certType: '',
  certNo: '',
  merName: '',
  merShortName: '',
  certStartDate: '',
  certEndDate: '',
  respPerson: '',
  regCap: '',
  certAddrProv: '',
  certAddrCity: '',
  certAddrDist: '',
  certAddrDet: '',
  latitude: 0,
  longitude: 0,
  bizAddrDet: '',
})

const options = ref<Option[]>([
  { text: '营业执照', value: '01', merType: ['1', '2'] },
  { text: '事业单位法人证书', value: '02', merType: ['4'] },
  { text: '身份证件', value: '03', merType: [] },
  { text: '其他证明文件', value: '04', merType: ['6'] },
  { text: '民办非企业单位登记证书', value: '05', merType: ['6'] },
  { text: '统一社会信用代码证书', value: '06', merType: ['5'] },
  { text: '社会团体法人证书', value: '07', merType: ['6'] },
  { text: '基金会法人登记证书', value: '08', merType: ['6'] },
  { text: '执业许可证/执业证', value: '09', merType: ['6'] },
  { text: '基层群众性自治组织特别法人统一社会信用代码证', value: '10', merType: ['6'] },
  { text: '农村集体经济组织登记证', value: '11', merType: ['6'] },
  { text: '宗教活动场所登记证', value: '12', merType: ['6'] },
  { text: '慈善组织公开募捐资格证书', value: '13', merType: ['6'] },
])
const canSelectedOptions = ref<Option[]>([])
canSelectedOptions.value = options.value.filter((option: Option) => option.merType.indexOf(mer_type.value) !== -1)
form.value.certType = canSelectedOptions.value[0].value

if (licenseInfo.value.certNo !== '') {
  form.value = licenseInfo.value
}

// 处理字段名称
let certTitle = ''
let respPersonTitle = ''
let regCapTitle = ''
let certAddrTitle = ''
let showRegCap = false
let showCertDate = true

function dealTitle () {
  if (mer_type.value === '1') {
    certTitle = '统一社会信用代码'
    respPersonTitle = '经营者'
    regCapTitle = '注册资本（万元）'
    showRegCap = false
    certAddrTitle = '注册地'
    showCertDate = true
  }
  if (mer_type.value === '2') {
    certTitle = '统一社会信用代码'
    respPersonTitle = '法定责任人'
    regCapTitle = '注册资本（万元）'
    showRegCap = true
    certAddrTitle = '注册地'
    showCertDate = true
  }
  if (mer_type.value === '4') {
    certTitle = '统一社会信用代码'
    respPersonTitle = '法定代表人'
    regCapTitle = '开办资金（万元）'
    showRegCap = true
    certAddrTitle = '住所'
    showCertDate = true
  }
  if (mer_type.value === '5') {
    if (form.value.certType === '02') {
      certTitle = '统一社会信用代码'
      respPersonTitle = '法定代表人'
      regCapTitle = '开办资金（万元）'
      showRegCap = true
      certAddrTitle = '住所'
      showCertDate = true
    }
    else if (form.value.certType === '06') {
      certTitle = '统一社会信用代码'
      respPersonTitle = '负责人'
      regCapTitle = '开办资金（万元）'
      showRegCap = false
      certAddrTitle = '注册地'
      showCertDate = false
    }
  }
  if (mer_type.value === '6') {
    certTitle = '证书编号'
    respPersonTitle = '责任人'
    regCapTitle = '开办资金（万元）'
    showRegCap = false
    certAddrTitle = '证照地址'
    showCertDate = true
  }
}

dealTitle()

function licenseValidator() {
  return new Promise((resolve) => {
    licenseUploader.value.validate().then((valid: boolean) => {
      resolve(valid)
    })
  })
}

function certNoFirstValidator (val: string) {
  if (mer_type.value === '6') {
    return true
  } else {
    return /^[a-zA-Z0-9]{18}$/.test(val)
  }
}

function certNoSecondValidator (val: string) {
  if (mer_type.value === '6') {
    return /^.{5,30}$/.test(val)
  } else {
    return true
  }
}

function certAddrValidator() {
  return form.value.certAddrProv !== ''
    && form.value.certAddrCity !== ''
    && form.value.certAddrDist !== ''
}

const rules = {
  certNo: [
    { required: true, message: `请输入${certTitle}` },
    { validator: certNoFirstValidator, message: '必须由18位的数字及字母构成' },
    { validator: certNoSecondValidator, message: '必须由5-30位的字符构成' }
  ],
  license: [
    { validator: licenseValidator, message: '请上传证件照图片' },
  ],
  merName: [
    { required: true, message: '请输入商户名称' },
  ],
  merShortName: [
    { required: true, message: '请输入商户简称' },
  ],
  certStartDate: [
    { required: true, message: '请输入执照起始日期' },
  ],
  certEndDate: [
    { required: true, message: '请输入执照终止日期' },
  ],
  respPerson: [
    { required: true, message: `请输入${respPersonTitle}` },
  ],
  regCap: [
    { required: true, message: `请输入${regCapTitle}` },
  ],
  certAddr: [
    { validator: certAddrValidator, message: `请输入${certAddrTitle}省市区` },
  ],
  certAddrDet: [
    { required: true, message: `请输入完整${certAddrTitle}` },
  ],
  // bizAddr: [
  //   { validator: bizAddrValidator, message: '请输入经营地址省市区' },
  // ],
  bizAddrDet: [
    { required: true, message: '请输入完整经营地址' },
  ],
}
function licenseUploaded(value: any) {
  form.value.merName = value.licenseInfo.merName
  form.value.merShortName = value.licenseInfo.merShortName
  form.value.certNo = value.licenseInfo.certNo.toLocaleUpperCase()
  form.value.certAddrDet = value.licenseInfo.certAddrDet
  form.value.certStartDate = value.licenseInfo.certStartDate
  form.value.certEndDate = value.licenseInfo.certEndDate
  form.value.regCap = value.licenseInfo.regCap
  form.value.respPerson = value.licenseInfo.respPerson
  form.value.certAddrProv = value.licenseInfo.certAddrProv
  form.value.certAddrCity = value.licenseInfo.certAddrCity
  form.value.certAddrDist = value.licenseInfo.certAddrDist
}

function clickNext() {
  console.log(form.value)
  // 表单校验
  ruleForm.value?.validate().then(({ valid }) => {
    if (valid) {
      // 先存数据
      form.value.certNo = form.value.certNo.toLocaleUpperCase()
      licenseInfo.value = form.value
      next()
    }
  })
}

watch(() => form.value.certType, () => {
  dealTitle()
})

// 处理输入事件
function handleInput(inputName, event) {
  const value = event
  // 使用正则表达式移除特殊字符和表情
  // const filteredValue = value.replace(/<[^>]+(>|$)|[^\w\u4E00-\u9FA5]/g, '')
  const filteredValue = value.replace(/[\<[^>]+(>|$)|[^\w\u4E00-\u9FA5〇()（）]/g, '')
  
  form.value[inputName] = filteredValue
}

function inputCert(inputName, event) {
  const value = event
  const filteredValue = value.toLocaleUpperCase()
  form.value[inputName] = filteredValue
}
</script>

<template>
  <div class="input">
    <steps-bar />
    <nut-form ref="ruleForm" :model-value="form" :rules="rules">
      <nut-form-item label="证件类型" prop="certType" required>
        <option-select v-model="form.certType" title="证件类型" :options="canSelectedOptions" inputAlign="right" />
      </nut-form-item>
      <nut-form-item required prop="license">
        <license-upload ref="licenseUploader" @uploaded="licenseUploaded" />
      </nut-form-item>

      <nut-form-item :label="certTitle" prop="certNo" required :label-width="certTitle === '证书编号' ? 90 : 140">
        <nut-input v-model="form.certNo" class="nut-input-text" :placeholder="`请输入${certTitle}`" type="text"
          input-align="right" placeholder-style="color:#ccc;" @input="inputCert('certNo', $event)" />
      </nut-form-item>

      <nut-form-item label="商户名称" prop="merName" required>
        <nut-textarea v-model="form.merName" class="nut-input-text" placeholder="请输入商户名称" type="text" autosize
          placeholder-style="color:#ccc;" max-length="50" @input="handleInput('merName', $event)" />
      </nut-form-item>
      <nut-form-item label="商户简称" prop="merShortName" required>
        <nut-textarea v-model="form.merShortName" class="nut-input-text" placeholder="请输入商户简称" type="text" autosize
          @input="handleInput('merShortName', $event)" placeholder-style="color:#ccc;" max-length="20" />
      </nut-form-item>
      <nut-form-item v-if="showCertDate" label="发证日期" prop="certStartDate" required :label-width="110">
        <date-picker v-model="form.certStartDate" title="发证日期" inputAlign="right" />
      </nut-form-item>
      <nut-form-item v-if="showCertDate" label="到期日期" prop="certEndDate" required :label-width="110">
        <date-picker v-model="form.certEndDate" title="到期日期" inputAlign="right" />
      </nut-form-item>
      <nut-form-item :label="respPersonTitle" prop="respPerson" required>
        <nut-input v-model="form.respPerson" class="nut-input-text" :placeholder="`请输入${respPersonTitle}`" type="text"
          input-align="right" placeholder-style="color:#ccc;" max-length="20" />
      </nut-form-item>
      <nut-form-item v-if="showRegCap" :label="regCapTitle" prop="regCap" required>
        <nut-input v-model="form.regCap" class="nut-input-text" :placeholder="`请输入${regCapTitle}`" type="text"
          input-align="right" placeholder-style="color:#ccc;" max-length="20" />
      </nut-form-item>
      <nut-form-item :label="`${certAddrTitle}省市区`" prop="certAddr" required :label-width="130">
        <addr-cascader :disabled="mer_type.value === '6'" v-model:prov="form.certAddrProv"
          v-model:city="form.certAddrCity" v-model:dist="form.certAddrDist" inputAlign="right" />
      </nut-form-item>
      <nut-form-item :label="certAddrTitle" prop="certAddrDet" required>
        <nut-textarea v-model="form.certAddrDet" class="nut-input-text" :placeholder="`请输入完整${certAddrTitle}`"
          type="text" autosize placeholder-style="color:#ccc;" max-length="45" />
      </nut-form-item>
      <nut-form-item prop="bizAddrDet" required custom-class="li-cell-box li-location-lable">
        <template #label>
          <div class="label" style="display: inline-block">
            <span style="vertical-align: middle;">经营地址</span>
            <div class="icon" style="display: inline-block;font-size: 22px;vertical-align: middle">
              <nut-icon name="location2" size="16px"></nut-icon>
            </div>
          </div>
        </template>
        <location-input v-model="form.bizAddrDet" v-model:latitude="form.latitude" v-model:longitude="form.longitude"
          placeholder="请选择经营地址" />
      </nut-form-item>
    </nut-form>
    <div class="button">
      <nut-button type="primary" custom-class="login-btn shake_o" block @click="clickNext">下一步</nut-button>
      <!-- <nut-button type="primary" block @click="clickNext">下一步</nut-button> -->
    </div>
  </div>
</template>

<route lang="json">
{
  "style": {
    "navigationBarTitleText": "商户进件",
    "backgroundColorContent": "#f1f1f1"
  }
}
</route>

<style lang="sass" scoped>
.input
  padding-bottom: 20px
  .loader
    width: 210px
    display: flex
    justify-content: space-between
  .button
    margin: 40px 20px

:deep(.nut-form-item__label)
  display: flex!important
  flex-direction: row!important
  min-width: 100px!important
:deep(.login-btn)
  width: 100%
  height: 85rpx
  margin-top: 30rpx
  background-color: #2196F3!important

:deep(.nut-textarea__textarea)
  text-align: right!important

:deep(.nut-uploader__upload)
  width: 100%!important

:deep(.nut-uploader__preview-img)
  width: 100%!important

:deep(.nut-step-main)
  margin-top: 20rpx
</style>
